import { ref, reactive, defineComponent } from 'vue'

import { NButton, NModal, NForm, NFormItem, NInput, FormInst, NSpace } from 'naive-ui'

import { wrapperRequest } from '@/utils'

interface ButtonRemarkFactoryOptions {
  title: string
  buttonText: string
}

const defaultOpt = { title: '', buttonText: '添加备注' }

declare class ButtonRemarkFactory {
  dialog: { visible: boolean }
  form: { remark: string }
  title: string
  buttonText: string
  submitting: boolean
  formRef: FormInst
  request<T>(...args: []): Promise<T>
  submit(): Promise<void>
  cancel(): void
  openDialog(): void
}

export function useButtonRemarkFactory(options?: Partial<ButtonRemarkFactoryOptions>) {
  const opt = { ...defaultOpt, ...options }

  const dialog = reactive({ visible: false })

  const form = reactive({ remark: '' })

  const title = ref(opt.title)
  const buttonText = ref(opt.buttonText)

  const submitting = ref(false)
  const formRef = ref<FormInst | null>(null)

  const request = function (remark: string) {
    return Promise.resolve(remark)
  }

  const onSuccess = null
  const beforeOpen = null

  return {
    dialog,
    form,
    title,
    buttonText,
    submitting,
    formRef,
    onSuccess,
    beforeOpen,
    request,
    submit() {
      return wrapperRequest(request).call(submitting, form.remark)
    },
    cancel() {
      dialog.visible = false
    },
    openDialog() {
      dialog.visible = true
    }
  }
}

export default defineComponent({
  name: 'ButtonRemarkFactory',
  render(this: ButtonRemarkFactory) {
    return (
      <NButton onClick={this.openDialog}>
        {this.buttonText}

        <NModal
          v-model:show={this.dialog.visible}
          title={this.title || this.buttonText}
          transformOrigin='center'
          to='body'
          v-slots={{
            footer: () => {
              return (
                <NSpace justify='end'>
                  <NButton onClick={() => (this.dialog.visible = false)}>取消</NButton>
                  <NButton type='primary' loading={this.submitting} onClick={this.submit}>
                    确定
                  </NButton>
                </NSpace>
              )
            }
          }}>
          <NForm model={this.form} labelWidth={80} labelPlacement='left' ref='formRef'>
            <NFormItem label='备注' path='remark'>
              <NInput v-model:value={this.form.remark} type='textarea' showCount />
            </NFormItem>
          </NForm>
        </NModal>
      </NButton>
    )
  }
})
